package cn.tedu.reflection;

import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/*测试暴力反射*/
public class TestReflect2 {
    @Test
    public void getfie2() throws Exception {
        Class<?> clazz = Person.class;
        Field field = clazz.getDeclaredField("name");
        System.out.println(field);
        System.out.println(field.getType());//class java.lang.String
        System.out.println(field.getType().getName());//java.lang.String

        /**设置属性的值
        * 1.需要指定到底给哪个对象的name属性设置值,没有对象就创建对象*/
        Object p1=clazz.newInstance();
        /*暴力反射,需要设置私有可见的权限*/
        field.setAccessible(true);
        /**通过字段对象field给刚建立的对象的属性设置值,
        * field.set(o,n);*/
        field.set(p1,"海绵宝宝");
        /**field.get(o)*/
        System.out.println(field.get(p1));

    }

    @Test
    public void fetfie3() throws Exception {
        Class<?> clazz = Person.class;
        Field field2 = clazz.getDeclaredField("age");
        System.out.println(field2);
        System.out.println(field2.getType());//int
        System.out.println(field2.getType().getName());//int
        Object p2 = clazz.newInstance();
        field2.setAccessible(true);
        field2.set(p2,36);
        System.out.println(field2.get(p2));
    }

    @Test
    public void getFunction2() throws Exception {
        Class<?> clazz = Person.class;
        /*getDeclaredMethod(n,x,y,z)
        * n:要获取的指定方法的方法名
        * x,y,z,可变参数,是指指定方法的参数类型,注意传入的是字节码对象
        * */
        Method method = clazz.getDeclaredMethod("save", int.class, String.class);
        //System.out.println(method);
        method.setAccessible(true);
        Object p3 = clazz.newInstance();
        /*invoke(o,x,y,z,...)表示通过反射执行方法
        * o:要给哪个对象执行上面获取到的save()
        * x,y,z,...执行save()时需要传入的参数
        * */

        method.invoke(p3,999,"感冒灵");
    }
    @Test
    public void getFunction3() throws Exception {
        Class<?> clazz = Person.class;
        Method method = clazz.getDeclaredMethod("update");
        method.setAccessible(true);
        Object p4 = clazz.newInstance();
        method.invoke(p4);
    }

    @Test
    public void getFunction4() throws Exception {
        Class<?> clazz = Person.class;
        Method method = clazz.getDeclaredMethod("add", String.class);
        method.setAccessible(true);
        Object p5 = clazz.newInstance();
        method.invoke(p5,"哈哈哈");
    }

}


